package utils

import (
	"context"
	"fmt"
	"log"
	"os"
	"strconv"
	"time"

	"github.com/go-redis/redis/v8"
)

func InitRedis() {
	redisAddr := os.Getenv("REDIS_ADDR")
	redisPassword := os.Getenv("REDIS_PASSWORD")
	redisDbStr := os.Getenv("REDIS_DB")
	// 将 REDIS_DB 转换为 int 类型，默认值为 0
	redisDb, err := strconv.Atoi(redisDbStr)
	if err != nil || redisDb < 0 {
		log.Printf("Invalid or missing REDIS_DB value: %v. Using default value 0.", redisDbStr)
		redisDb = 0
	}
	RedisClient = redis.NewClient(&redis.Options{
		Addr:     redisAddr,
		Password: redisPassword,
		DB:       redisDb,
	})

	pong, err := RedisClient.Ping(context.Background()).Result()
	if err != nil {
		log.Fatalf("Redis connection failed: %v", err)
	}
	fmt.Println("Redis connected:", pong)
}

func SetRedis(key string, value interface{}, expiration int) error {
	ctx := context.Background()
	err := RedisClient.Set(ctx, key, value, time.Duration(expiration)*time.Second).Err()
	if err != nil {
		return err
	}
	return nil
}

func GetRedis(key string) string {
	ctx := context.Background()
	value, err := RedisClient.Get(ctx, key).Result()
	if err != nil {
		return ""
	}
	return value
}
